<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: 0 }"
      :body-style="{
        paddingTop: '20px',
      }"
      :title="$t('workplace.contentData')"
    >
      <!-- 添加 Task ID 下拉框 -->
      <div v-if="showSelectors" style="margin-bottom: 20px;">
        <a-select
          v-model="taskId"
          placeholder="Select Task ID"
          style="width: 320px;"
        >
      <a-option v-for="task in tasks" :key="task.id" :value="task.id">
          {{ task }}
      </a-option>
        </a-select>
      </div>
      <!-- 添加员工和时间段的下拉框 -->
      <div
        v-if="showSelectors"
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
        "
      >
        <a-select
          v-model="selectedEmployee"
          :style="{ width: '320px' }"
          placeholder="Select Employee"
        >
          <a-option v-for="Employee in employeeOptions" :key="Employee.id"
            >{{ Employee.id }} - {{ Employee.name }}</a-option
          >
        </a-select>

        <a-select
          v-model="selectedPeriod"
          :style="{ width: '320px' }"
          placeholder="Select Period"
        >
          <a-option v-for="period in periodOptions" :key="period">{{
            period
          }}</a-option>
        </a-select>
      </div>

      <!-- 添加 查询 和 重置 按钮 -->
      <div v-if="showSelectors" style="margin-bottom: 20px; text-align: right;">
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button style="margin-left: 10px;" @click="handleReset">重置</a-button>
      </div>

      <template #extra>
        <a-link @click="toggleSelectors">{{ $t('workplace.viewMore') }}</a-link>
      </template>

      <!-- 使用 a-row 和 a-col 分成左右两部分 -->
      <a-row :gutter="16">
        <!-- 左侧柱状图 -->
        <a-col :span="12">
          <Chart style="width: 100%; height: 350px;" :option="chartOption" />
        </a-col>
        <!-- 右侧饼状图 -->
        <a-col :span="12">
          <Chart height="350px" :option="pieChartOption" />
        </a-col>
      </a-row>
    </a-card>
    <!-- 插入新的卡片，显示热门内容 -->
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: '0' }"
      :body-style="{ padding: '17px 20px 21px 20px' }"
      style="width: 50%; margin-top: 20px;"
    >
      <template #title>
        Entitlements by category
      </template>
      <!-- <template #extra>
        <a-link>{{ $t('workplace.viewMore') }}</a-link>
      </template> -->

      <a-space direction="vertical" :size="10" fill>
        <!-- 修改单选按钮组 -->
        <a-radio-group
          v-model:model-value="type"
          type="button"
          @change="typeChange"
        >
          <a-radio value="annual_leave">
            {{ $t('$ Annual Leave') }}
          </a-radio>
          <a-radio value="ord">
            {{ $t('$ ORD') }}
          </a-radio>
          <a-radio value="overtime">
            {{ $t('$ Overtime') }}
          </a-radio>
          <a-radio value="other_leave">
            {{ $t('$ Other Leave') }}
          </a-radio>
          <a-radio value="sleepover">
            {{ $t('$ Sleepover') }}
          </a-radio>
        </a-radio-group>


        <!-- 表格展示经过过滤后的数据 -->
        <a-table  
          :data="filteredList"
          :pagination="false"
          :bordered="false"
          :scroll="{ x: '100%', y: '264px' }"
          >
          <template #columns>
            <!-- 列1: 类别 -->
            <a-table-column title="category" data-index="x">
              <template #cell="{ record }">
                <a-typography-paragraph
                  :ellipsis="{
                    rows: 1,
                  }"
                >
                  {{ record.x }}
                  <!-- 每行类别后面添加一个小问号提示 -->
                  <a-popover title="Clause Reference">
                    <a-button shape="circle" style="margin-left: 5px;">?</a-button>
                    <template #content>
                      {{ record.z }}
                    </template>
                  </a-popover>
                </a-typography-paragraph>
              </template>
            </a-table-column> 

            <!-- 列2: 金额 -->
            <a-table-column title="Entitlement $" data-index="y">
              <template #cell="{ record }">
                <a-typography-paragraph>
                  {{ record.y.toFixed(2) }}
                </a-typography-paragraph>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-space>
    </a-card>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, onMounted,computed } from 'vue';
  import axios from 'axios';
  import useLoading from '@/hooks/loading';
  import { queryContentData, queryEmployeeData } from '@/api/dashboard';
  import useChartOption from '@/hooks/chart-option';
  import { ToolTipFormatterParams } from '@/types/echarts';
  import { AnyObject } from '@/types/global';
  import eventBus from '@/eventBus';
  import baseUrl from '../../../../config';

  // 在 <script setup> 中定义 props
  const props = defineProps({
    selectedEmployee: String,
    selectedPeriod: String,
    taskId: String
  });
  // 使用 ref 从 props 中获取响应式引用
  const selectedEmployee = ref(props.selectedEmployee);
  const selectedPeriod = ref(props.selectedPeriod);
  const taskId = ref(props.taskId);
  const tasks = ref([]);
  const emit = defineEmits(['query']);
  const { loading, setLoading } = useLoading(true);
  const xAxis = ref<string[]>([]);
  const chartsData = ref<number[]>([]);
  const showSelectors = ref(false);
  const employeeOptions = ref([
    { name: 'Nate Wang', id: '123', disabled: false },
    { name: 'Dusica LAPCEVIC', id: '232', disabled: false },
    { name: 'Hao Chen', id: '2321', disabled: false },
    { name: 'Disabled', id: '2312', disabled: true },
  ]);
  const periodOptions = ref([]);
  // 当组件加载时调用API获取任务标题
  onMounted(async () => {
    try {
      const response = await axios.get(`${baseUrl}/api/file-task/titles`);
      console.log('3333333333333:', response.data);
      tasks.value = response.data; // 假设接口返回的数据是 { data: [...] }
    } catch (error) {
      console.error('Error fetching task titles:', error);
    }
  });

  function graphicFactory(side: AnyObject) {
    return {
      type: 'text',
      bottom: '8',
      ...side,
      style: {
        text: '',
        textAlign: 'center',
        fill: '#4E5969',
        fontSize: 12,
      },
    };
  }
  const graphicElements = ref([
    graphicFactory({ left: '2.6%' }),
    graphicFactory({ right: 0 }),
  ]);

  // 柱状图配置
  const { chartOption } = useChartOption(() => {
    return {
      title: {
        text: 'Review Period',  // 添加标题
        left: 'center',  // 将标题居中
        top: '5%',  // 设置标题距离顶部的距离
        textStyle: {
          fontSize: 16,  // 设置标题字体大小
          fontWeight: 'bold',  // 加粗标题
          color: '#ff9800'  // 设置标题颜色
        }
      },
      grid: {
        left: '6%', // 增大左侧边距以避免纵坐标数值显示不全
        right: '36',
        top: '15%', // 增大顶部边距以防止柱子顶部的数值显示不全
        bottom: '120',
      },
      yAxis: {
        type: 'category',
        offset: 2,
        data: xAxis.value,
        boundaryGap: true, // 将 boundaryGap 设置为 true 以适应柱状图
        axisLabel: {
          // color: '#4E5969',
          rotate: 0, // 改为横向显示
      },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: true,
          interval: (idx: number) => {
            if (idx === 0) return false;
            if (idx === xAxis.value.length - 1) return false;
            return true;
          },
          lineStyle: {
            color: '#E5E8EF',
          },
        },
        axisPointer: {
          show: true,
          lineStyle: {
            color: '#23ADFF',
            width: 2,
          },
        },
      },
      xAxis: {
        type: 'value',
        axisLine: {
          show: false,
        },
        axisLabel: {
          formatter(value: any, idx: number) {
            if (idx === 0) return value;
            return `${value / 1000}k`;
          },
          margin: 15, // 增大纵坐标数值的间距，避免数字被遮挡
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#E5E8EF',
          },
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter(params) {
          const [firstElement] = params as ToolTipFormatterParams[];
          return `<div>
            <p class="tooltip-title">${firstElement.axisValueLabel}</p>
            <div class="content-panel"><span>amount</span><span class="tooltip-value">${Number(
              firstElement.value
            ).toLocaleString()}</span></div>
          </div>`;
        },
        className: 'echarts-tooltip-diy',
      },
      graphic: {
        elements: graphicElements.value,
      },
      series: [
        {
          data: chartsData.value,
          type: 'bar', // 将类型修改为 'bar' 以显示柱状图
          barWidth: '60%', // 设置柱子的宽度
          itemStyle: {
            color: '#ff9800', // 设置柱子的颜色为淡蓝色
          },
          label: {
            show: true, // 显示数值
            position: 'right', // 数值显示在柱子顶部
            formatter: (params) => {
              return `$${(Number(params.value) / 1000).toFixed(0)}k`; // 格式化显示为 "$344k" 等
            },
            color: '#ff9800', // 数值的颜色
            fontSize: 12, // 数值的字体大小
            distance: 10, // 数值与柱顶的距离，增大以避免被遮挡
          },
        },
      ],
    };
  });

  // 定义你的数据类别和相应的数据
  const categories = ref(['$ Annual Leave', '$ ORD', '$ Overtime', '$ Other Leave', '$ Sleepover']);
  // 根据类别名称决定颜色的函数
  const getColorByCategory = (category: string): string => {
    switch (category) {
      case '$ Annual Leave':
        return '#4caf50';  // 绿色
      case '$ ORD':
        return '#ff9800';  // 橙色
      case '$ Overtime':
        return '#2196f3';  // 蓝色
      case '$ Other Leave':
        return '#f44336';  // 红色
      case '$ Sleepover':
        return '#9c27b0';  // 紫色
      default:
        return '#607d8b';  // 默认灰色
    }
  };
  // 饼状图配置
  const pieChartOption = ref({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      top: '0%',  // 调整这个值，增大数值让图例离饼图更远
      left: 'center',
      textStyle: {
        color: '1'  // 适当暗淡的字体颜色
      }
    },
    series: [
      {
        name: 'Data',
        type: 'pie',
        radius: ['50%', '70%'],  // 设置内外半径
        center: ['50%', '50%'],  // 环形图中心位置
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1,
        },
        // 确保 xAxis.value 和 chartsData.value 的长度匹配
        data: xAxis.value.map((x, index) => {
          return {
            name: x,
            value: chartsData.value[index],  // 确保 chartsData.value 存在且长度与 xAxis.value 一致
            itemStyle: {
              color: getColorByCategory(x),  // 使用函数来决定颜色
            },
          };
        }),
        label: {
          formatter: '{d}%',  // 标签显示百分比
          fontSize: 14,
          color: '#4E5999',
          position: 'outside',  // 将标签放在外部s
        },
        
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',  // 设置高亮时的阴影效果
          },
        },
      },
    ]
    ,
  });
  // 查询数据
  function fetchData() {
    setLoading(true);
    const employeeNo = (selectedEmployee.value || '').replace(/\s+/g, '').split('-')[0];
    // eslint-disable-next-line camelcase
    const pseriod_str = (selectedPeriod.value || '').replace(/\s+/g, '');
    queryEmployeeData(taskId.value, employeeNo, pseriod_str)
      .then((response) => {
        employeeOptions.value = response.data.employees.map((employee) => ({
          name: employee[0],
          id: employee[1],
          disabled: false,
        }));
        console.log(response.data.period_list);
        periodOptions.value = response.data.period_list.map(
          (period) => (period == null ? 'N/A' : period.toString()) // 使用条件运算符检查null或undefined
        );
        queryContentData(
          selectedEmployee.value,
          taskId.value,
          selectedPeriod.value
        )
          .then((data) => {
            // console.log("data",data.data.results)
            xAxis.value = data.data.results.map((el) => el.x);
            chartsData.value = data.data.results.map((el) => el.y);
            // 更新 pieChartOption 数据
            pieChartOption.value.series[0].data = xAxis.value.map((x, index) => ({
              name: x,
              value: chartsData.value[index] ?? 0,  // 确保 chartsData.value 存在
              itemStyle: {
                color: getColorByCategory(x),  // 根据类别获取颜色
              }
            }));
            setLoading(false);
          })
          .catch((error) => {
            console.error('Failed to fetch content data:', error);
            setLoading(false);
          });
      })
      .catch((error) => {
        console.error('Failed to fetch employee data:', error);
        setLoading(false);
      });
  }
 
 
  // 重置按钮点击时触发
  function handleReset() {
    taskId.value = '';
    selectedEmployee.value = '';
    selectedPeriod.value = '';
    periodOptions.value = [];
  }
  function toggleSelectors() {
    showSelectors.value = !showSelectors.value;
  }



  const type = ref('annual_leave'); // 当前选中的类型
  const fullData = ref([]); // 后端返回的所有数据

  // 模拟获取数据
  const fetchData2 = async () => {
    loading.value = true;
    try {

      // 构建查询参数
      const params = {
        employee: selectedEmployee.value || '', // 员工编号
        period: selectedPeriod.value || '', // 时间段
        task_id: taskId.value || '' // Task ID
      };
      const response = await axios.get(`${baseUrl}/api/dashboard_list`, {params}); // 调用后端接口
      fullData.value = response.data.results;
    } finally {
      loading.value = false;
    }
  };
  // 查询按钮点击时触发
  function handleQuery() {
    fetchData(); // 调用自己的查询逻辑
    fetchData2(); // 调用自己的查询逻辑
    // 广播查询事件
    eventBus.emit('execute-query', { employee: selectedEmployee.value, task: taskId.value, period: selectedPeriod.value });
  }
  // 根据选中的类型过滤数据
  const filteredList = computed(() => {
    const selectedCategory = fullData.value.find(item => item.category === type.value);
    return selectedCategory ? selectedCategory.fields : [];
  });

  // 切换类型时的处理逻辑
  const typeChange = (selectedType: string) => {
    console.log('切换类型为:', selectedType);
  };


  // 组件挂载时获取数据
  onMounted(() => {
    fetchData();
    fetchData2();
    console.log('检查 chartOption',chartOption.value);  // 检查 chartOption
  });
</script>

<style scoped lang="less"></style>
